package com.itheima.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class MovementJob {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void syncMovement() {
        System.out.println("同步推荐动态开始");
        // 获取推荐动态的所有key
        Set<String> keys = stringRedisTemplate.keys("QUANZI_PUBLISH_RECOMMEND_*");
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                // 获取推荐用户的userId
                Long userId = Long.valueOf(key.replaceAll("QUANZI_PUBLISH_RECOMMEND_", ""));
                // 查询推荐动态的pid列表
                String pidStr = stringRedisTemplate.opsForValue().get(key);
                // 清除原有数据
                stringRedisTemplate.delete(key);
                mongoTemplate.remove(Query.query(Criteria.where("userId").is(userId)), RecommendMovement.class);
                // 保存推荐数据
                for (String pid : pidStr.split(",")) {
                    // 根据pid查询动态详情
                    Movement movement = mongoTemplate.findOne(Query.query(Criteria.where("pid").is(Long.parseLong(pid))), Movement.class);
                    // 封装 recommendMovement
                    RecommendMovement recommendMovement = new RecommendMovement();
                    recommendMovement.setCreated(System.currentTimeMillis());
                    recommendMovement.setUserId(userId);
                    recommendMovement.setPid(movement.getPid());
                    recommendMovement.setPublishId(movement.getId());
                    recommendMovement.setScore(RandomUtil.randomDouble(60, 100));
                    // 保存到mongo中
                    mongoTemplate.save(recommendMovement);

                }
            }
            System.out.println("同步推荐动态结束");
        }

    }
}
